package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.JobTypeInitEnum;
import com.ruoyi.common.enums.YnStatusEnum;
import com.ruoyi.system.domain.AppCreateJobBill;
import com.ruoyi.system.domain.HomeJobDomain;
import com.ruoyi.system.domain.JobPersonnelBuilder;
import com.ruoyi.system.domain.JobPlanBillDeclare;
import com.ruoyi.system.entity.AppJobSignedConfig;
import com.ruoyi.system.mapper.AppCreateJobBillMapper;
import com.ruoyi.system.mapper.JobPlanBillDeclareMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.AppJobSignedConfigService;
import com.ruoyi.system.service.JobPlanBillDeclareService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HomeJobServiceImpl {
    @Value("#{${app.job.type.config}}")
    private Map<Integer, String> appJobTypeConfig;
    @Autowired
    private AppCreateJobBillMapper appCreateJobBillMapper;
    @Autowired
    private JobPlanBillDeclareMapper jobPlanBillDeclareMapper;
    @Autowired
    private JobPlanBillDeclareService jobPlanBillDeclareService;
    @Autowired
    private AppJobSignedConfigService appJobSignedConfigService;
    @Autowired
    private SysUserMapper sysUserMapper;

    public HomeJobDomain homeJobCount(Long userId) {
        HomeJobDomain homeJobDomain = new HomeJobDomain();

        JobPlanBillDeclare jobPlanBillDeclare = new JobPlanBillDeclare();
        jobPlanBillDeclare.setApplyPeopleId(userId.toString());
        jobPlanBillDeclare.setYn(YnStatusEnum.Y.getCode());
        List<JobPlanBillDeclare> jobPlanBillDeclares = jobPlanBillDeclareService.queryAll(jobPlanBillDeclare);

        if (CollectionUtils.isEmpty(jobPlanBillDeclares)) {
            homeJobDomain.setApply(YnStatusEnum.N.getCode());
        } else {
            List<String> list = jobPlanBillDeclares.stream().map(JobPlanBillDeclare::getBillNumber).collect(Collectors.toList());
            List<AppCreateJobBill> appCreateJobBills = appCreateJobBillMapper.queryInPtw(list);
            if (!CollectionUtils.isEmpty(appCreateJobBills)) {
                homeJobDomain.setApply(appCreateJobBills.size());
            } else {
                homeJobDomain.setApply(YnStatusEnum.N.getCode());
            }
        }

        /*
         *  1.查询所有作业票
         *  2.根据作业票查询签批人
         *  3.判断票据是否签字
         *
         */
        Integer signed = 0;
        Integer sign = 0;
        List<String> array = new ArrayList<>();
        List<String> signArray = new ArrayList<>();
        List<AppCreateJobBill> appCreateJobBills = new ArrayList<>();

        AppCreateJobBill appCreateJobBill = new AppCreateJobBill();
        appCreateJobBill.setYn(YnStatusEnum.Y.getCode());
        List<AppCreateJobBill> createJobBills = appCreateJobBillMapper.queryAll(appCreateJobBill);

        List<String> list = createJobBills.stream().map(AppCreateJobBill::getPtw).collect(Collectors.toList());
        List<JobPlanBillDeclare> jobPlanBillDeclareListCase = jobPlanBillDeclareMapper.queryInPtw(list);
        Map<String, List<JobPlanBillDeclare>> map = jobPlanBillDeclareListCase.stream().collect(Collectors.groupingBy(JobPlanBillDeclare::getBillNumber));

        //方案一 最优性能1s
        AppJobSignedConfig appJobSignedConfig = new AppJobSignedConfig();
        appJobSignedConfig.setSignedBy(userId.intValue());
        List<AppJobSignedConfig> appJobSignedConfigList = appJobSignedConfigService.queryAll(appJobSignedConfig);

        //查询所有用户
        List<SysUser> userList = sysUserMapper.selectUserListNoParam();
        userList = userList.stream().filter(var -> var.getVid() != null).collect(Collectors.toList());
        Map<Integer, List<SysUser>> collected = userList.stream().collect(Collectors.groupingBy(SysUser::getVid));

        //根据类型加等级分组
        Map<String, List<AppJobSignedConfig>> listMap = appJobSignedConfigList.stream().collect(Collectors.groupingBy(AppJobSignedConfig::getJobType));
        if (!CollectionUtils.isEmpty(createJobBills)) {
            List<String> asList = Collections.singletonList("1,3,4,5,6");
            //根据票找签批组人员
            for (AppCreateJobBill var : createJobBills) {
                List<AppJobSignedConfig> appJobSignedConfigs = new ArrayList<>();
                //获取人员
                List<JobPlanBillDeclare> planBillDeclares = map.get(var.getPtw());

                List<SysUser> sysUserList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(planBillDeclares)) {
                    JobPlanBillDeclare planBillDeclare = planBillDeclares.stream().findFirst().orElse(new JobPlanBillDeclare());
                    List<JobPersonnelBuilder> jobPersonnelBuilders = JSON.parseArray(planBillDeclare.getJobPersonnel(), JobPersonnelBuilder.class);
                    for (JobPersonnelBuilder value : jobPersonnelBuilders) {
                        if ("out".equals(value.getType())) {
                            List<SysUser> sysUsers = collected.get(value.getId());
                            if (!CollectionUtils.isEmpty(sysUsers)) {
                                for (SysUser sysUser : sysUsers) {
                                    if ("0".equals(sysUser.getDelFlag())) {
                                        sysUserList.add(sysUser);
                                    }
                                }
                            }
                        }
                    }
                }

                if (!CollectionUtils.isEmpty(sysUserList)) {
                    List<Long> collect = sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
                    if (collect.contains(userId)) {
                        convertHeadMessage(var, sysUserList, appJobSignedConfigs);
                    }
                }

                if (asList.contains(var.getJobType()) && appJobTypeConfig.containsKey(Integer.valueOf(var.getJobType()))) {
                    //获取节点
                    String s = appJobTypeConfig.get(Integer.valueOf(var.getJobType()));

                    String[] split = s.split(",");
                    for (String vars : split) {
                        AppJobSignedConfig appJobSignedConfig1 = new AppJobSignedConfig();
                        appJobSignedConfig1.setJobType(var.getJobType());
                        appJobSignedConfig1.setNodeName(vars);
                        appJobSignedConfig1.setSignedBy(Integer.valueOf(planBillDeclares.stream().findFirst()
                                .orElse(new JobPlanBillDeclare()).getJobPersonChargeId()));
                        appJobSignedConfig1.setSignedName(planBillDeclares.stream().findFirst().orElse(new JobPlanBillDeclare()).getJobPersonCharge());
                        appJobSignedConfigs.add(appJobSignedConfig1);
                    }
                }

                String content = var.getContent();
                JSONObject jsonObject = JSON.parseObject(content);
                if (null == jsonObject) {
                    continue;
                }

                boolean flag = false;
                String key = var.getJobType();
                List<AppJobSignedConfig> configList = listMap.get(key);

                if (!CollectionUtils.isEmpty(configList)) {
                    String grade = "";
                    if ("1".equals(key)) {
                        grade = jsonObject.containsKey("zyjb") ? jsonObject.get("zyjb").toString()
                                : jsonObject.containsKey("Grade") ? jsonObject.get("Grade").toString()
                                : null;
                    }
                    if ("2".equals(key)) {
                        grade = jsonObject.containsKey("dhzyjb") ? jsonObject.get("dhzyjb").toString()
                                : jsonObject.containsKey("Grade") ? jsonObject.get("Grade").toString()
                                : null;
                    }
                    if ("3".equals(key)) {
                        grade = jsonObject.containsKey("zyjb") ? jsonObject.get("zyjb").toString()
                                : jsonObject.containsKey("Grade") ? jsonObject.get("Grade").toString()
                                : null;
                    }
                    Map<String, List<AppJobSignedConfig>> collect = configList.stream().collect(Collectors.groupingBy(AppJobSignedConfig::getJobGrade));
                    configList = collect.get(grade);
                }

                if (CollectionUtils.isEmpty(configList)) {
                    if (CollectionUtils.isEmpty(appJobSignedConfigs)) {
                        continue;
                    }
                    configList = appJobSignedConfigs;
                    flag = true;
                }

                if (!flag) {
                    if (!CollectionUtils.isEmpty(appJobSignedConfigs)) {
                        configList.addAll(appJobSignedConfigs);
                    }
                }

                for (AppJobSignedConfig varOne : configList) {
                    if (array.contains(var.getSpecialNumber())) {
                        continue;
                    }
                    String nodeName = varOne.getNodeName();
                    if (!jsonObject.containsKey(nodeName) || jsonObject.get(nodeName) == null) {
                        if (jsonObject.get(nodeName) == null) {
                            String specialNumber = var.getSpecialNumber();
                            array.add(specialNumber);

                            appCreateJobBills.add(var);

                            signed++;
                        }
                    }
                }

                List<String> init = new ArrayList<>();
                List<String> collect = configList.stream().map(AppJobSignedConfig::getNodeName).collect(Collectors.toList());
                for (String varBase : collect) {
                    if (jsonObject.containsKey(varBase) || jsonObject.get(varBase) != null) {
                        if (jsonObject.get(varBase) != null) {
                            init.add(varBase);
                        }
                    }
                }

                if (init.size() == collect.size()) {
                    String specialNumber = var.getSpecialNumber();
                    signArray.add(specialNumber);
                    sign++;
                }
            }
        }

        homeJobDomain.setSigned(signed);
        homeJobDomain.setSign(sign);
        if (CollectionUtils.isEmpty(appCreateJobBills)) {
            homeJobDomain.setAppCreateJobBillList(new ArrayList<>());
            return homeJobDomain;
        }

        appCreateJobBills.forEach(var -> {
            List<JobPlanBillDeclare> planBillDeclares = map.get(var.getPtw());
            if (!CollectionUtils.isEmpty(planBillDeclares)) {
                var.setPwtId(Objects.requireNonNull(planBillDeclares.stream().findFirst().orElse(new JobPlanBillDeclare())).getId());
            }
        });
        homeJobDomain.setAppCreateJobBillList(appCreateJobBills);

        return homeJobDomain;
    }

    private void convertHeadMessage(AppCreateJobBill var, List<SysUser> sysUserList, List<AppJobSignedConfig> appJobSignedConfigs) {
        if (CollectionUtils.isEmpty(sysUserList)) {
            return;
        }

        String content = var.getContent();
        JSONObject jsonObject = JSON.parseObject(content);
        if (null == jsonObject) {
            return;
        }

        if (var.getJobType().equals(JobTypeInitEnum.HOT_WORK_SECURITY_JOB_BILL.getCode().toString())) {
            List<String> asList = Arrays.asList("qianmingDt7", "yjqm7");
            String dhzyjb = jsonObject.get("dhzyjb").toString();
            if ("二级（72H）".equals(dhzyjb)) {
                for (String value : asList) {
                    for (SysUser sysUser : sysUserList) {
                        AppJobSignedConfig appJobSignedConfig = new AppJobSignedConfig();
                        appJobSignedConfig.setNodeName(value);
                        appJobSignedConfig.setSignedBy(sysUser.getUserId().intValue());
                        appJobSignedConfig.setSignedName(sysUser.getNickName());
                        appJobSignedConfigs.add(appJobSignedConfig);
                    }
                }
            }






        }









    }

}
